package com.keya.config;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * .
 *
 * @author : xf.he
 * @version : 1.0 2023/6/25
 * @since : 1.0
 **/
public class StringArrayTypeHandler extends BaseTypeHandler<String[]> {
    private final ObjectMapper mapper = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String[] parameter, JdbcType jdbcType) throws SQLException {
        try {
            ps.setString(i, mapper.writeValueAsString(parameter) + "[]");
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Error converting String array to JSON", e);
        }
    }

    @Override
    public String[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return parseJsonArray(rs.getString(columnName));
    }

    @Override
    public String[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return parseJsonArray(rs.getString(columnIndex));
    }

    @Override
    public String[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return parseJsonArray(cs.getString(columnIndex));
    }

    private String[] parseJsonArray(String jsonString) {
        if (StringUtils.isBlank(jsonString)) {
            return new String[0];
        }
        try {
            return mapper.readValue(jsonString.substring(0, jsonString.length() - 2), String[].class);
        } catch (IOException e) {
            throw new RuntimeException("Error reading JSON from database: " + jsonString, e);
        }
    }
}
